//
//  MYGImagesUploadView.swift
//  MYGrow
//
//  Created by lance on 2024/3/3.
//

import UIKit
import TZImagePickerController
import QMUIKit
class MYGImagesUploadView: UIView {
    // MARK: - Property
    var contentInset: UIEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 0, right: 15)
    var itemSpacing = 7.5
    var lineSpacing = 7.5
    var itemPerRow = 3
    var maximumImageCount = 9
    var canAddImage = true
    var imagesChangeAction: (([MYGImagesUploadViewImageModel]) -> ())?
    
    private var itemWidth:CGFloat {
        let containerMargin = contentInset.left + contentInset.right
        let totalItemSpacing = itemSpacing > 1 ? itemSpacing * (Double(itemPerRow) - 1.0) : 0
        let total = containerMargin + totalItemSpacing
        let width = (screenWidth - total) / Double(itemPerRow)
        return width
    }
    
    private var itemModels: [MYGImagesUploadViewImageModel] = []
    private var showUplaodCell: Bool {
        get {
            canAddImage && itemModels.count < maximumImageCount
        }
    }
    
    private var itemCount: Int {
        get {
            showUplaodCell ? itemModels.count + 1 : itemModels.count
        }
    }
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        configUI()
        reload(with: [])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI
    private func configUI() {
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.height.equalTo(0)
        }
    }
    
    // MARK: - Public funcs
    func reload(with imageModels: [MYGImagesUploadViewImageModel]) {
        itemModels = imageModels
        let mod = itemCount % 3
        let rows = mod == 0 ? (itemCount / 3) : (itemCount / 3 + 1)
        let inset = contentInset.top + contentInset.bottom
        let totalSpacing = rows == 0 ? 0.0 : CGFloat(rows - 1) * lineSpacing
        let height = CGFloat(rows) * itemWidth + totalSpacing + inset
        collectionView.snp.updateConstraints { make in
            make.height.equalTo(height + 1)
        }
        collectionView.reloadData()
    }
    
    // MARK: - lazy load
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isScrollEnabled = false
        collectionView.register(cellWithClass: MYGImagesUploadViewImageCell.self)
        collectionView.register(cellWithClass: MYGImagesUploadViewUploadCell.self)
        return collectionView
    }()
}

extension MYGImagesUploadView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        itemCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if (showUplaodCell && indexPath.row == itemModels.count) {
            let cell = collectionView.dequeueReusableCell(withClass: MYGImagesUploadViewUploadCell.self, for: indexPath)
            return cell
        }

        let cell = collectionView.dequeueReusableCell(withClass: MYGImagesUploadViewImageCell.self, for: indexPath)
        cell.model = itemModels[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if (showUplaodCell && indexPath.row == itemModels.count) {
            showImagePicker()
        } else {
            guard let cell = collectionView.cellForItem(at: indexPath) as? MYGImagesUploadViewImageCell else { return }
            let vc = QMUIImagePreviewViewController()
            vc.imagePreviewView.delegate = self
            vc.imagePreviewView.currentImageIndex = UInt(indexPath.row)
            vc.sourceImageView = {
                return cell.imageView
            }
            vc.presentingStyle = .zoom
            vc.dismissingStyle = .fade
            UIViewController.currentViewController?.present(vc, animated: true)
        }
    }
    
}

extension MYGImagesUploadView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        CGSize(width: itemWidth, height: itemWidth)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        lineSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        itemSpacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        contentInset
    }
}

extension MYGImagesUploadView {
    func showImagePicker() {
        let picker = TZImagePickerController(maxImagesCount: 1, delegate: self)!
        picker.maxImagesCount = maximumImageCount - itemModels.count
        picker.allowPickingVideo = false
        picker.allowTakePicture = true
        UIViewController.currentViewController?.present(picker, animated: true)
    }
}

extension MYGImagesUploadView: TZImagePickerControllerDelegate {
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        for photo in photos {
            let imageModel = MYGImagesUploadViewImageModel(image: photo)
            itemModels.append(imageModel)
        }
        
        reload(with: itemModels)
        imagesChangeAction?(itemModels)
    }
}


extension MYGImagesUploadView: QMUIImagePreviewViewDelegate {
    func numberOfImages(in imagePreviewView: QMUIImagePreviewView!) -> UInt {
        return UInt(itemModels.count)
    }
    
    func imagePreviewView(_ imagePreviewView: QMUIImagePreviewView!, renderZoomImageView zoomImageView: QMUIZoomImageView!, at index: UInt) {
        guard let cell = collectionView.cellForItem(at: IndexPath(item: Int(index), section: 0)) as? MYGImagesUploadViewImageCell else { return }
        zoomImageView.image = cell.imageView.image
    }
}
